<template>
  <div class="upload">

    <el-upload
      v-if="uploadVisible"
      :action="uploadUrl"
      :limit="limit"
      :name="name"
      :accept="accept"
      :disabled="disabled"
      :show-file-list="false"
      :on-success="handleImageSuccess"
      :on-error="handleImageError"
    >
      <el-button size="small" type="primary"><slot /></el-button>
      <!--      <div slot="tip" class="el-upload__tip">只能上传{{ accept }}文件，且不超过{{ size }}M</div>-->
    </el-upload>
  </div>
</template>

<script>

import { Notification } from 'element-ui'
/**
 * 上传文件组件
 */
export default {
  name: 'UploadAttachment',
  props: {
    value: {
      type: String,
      default: ''
    },
    /** 上传的文件字段名 */
    name: {
      type: String,
      default: ''
    },
    /** 接受上传的文件类型 */
    accept: {
      type: String,
      default: ''
    },
    /** 最大允许上传个数,默认1 */
    limit: {
      type: Number,
      default: 1
    },
    /** 最是否禁用,默认false */
    disabled: {
      type: Boolean,
      default: false
    },
    /** 最是否禁用,默认2M */
    size: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      uploadVisible: true,
      uploadUrl: this.domain + '/nt/contract/imports',
      attachment: []
    }
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
      this.$emit('change', val)
    },
    // 上传成功回调
    handleImageSuccess(response, file, fileList) {
      if (response.code !== 20000) {
        Notification.error({
          title: '错误',
          message: response.msg || '上传失败'
        })
      } else {
        this.emitInput(response.data)
        Notification.success({
          title: '提示',
          message: '导入成功'
        })
        this.uploadVisible = false
        this.$nextTick(() => {
          // 重新创建组件
          this.uploadVisible = true
        })
      }
    },
    // 上传失败回调
    handleImageError(err, file, fileList) {
      Notification.error({
        title: '错误',
        message: err.msg || '上传失败'
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
